package com.gouaixin.bee.beeframework2.extra.myutils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.webkit.WebView;

public class YHttpUtil {

	public static void post(final String url, final String json,
			final ResponseListener responseListener) {
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Looper.prepare();
				final String urlPath = url;
				Log.e("main","请求url="+urlPath);
				Log.e("main","请求json="+json);
				URL url;
				try {
					url = new URL(urlPath);
					/* 把JSON数据转换成String类型使用输出流向服务器写 */
					String content = json;
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setConnectTimeout(5000);
					conn.setDoOutput(true);// 设置允许输出
					conn.setRequestMethod("POST");
					conn.setRequestProperty("User-Agent", "Fiddler");
					conn.setRequestProperty("Content-Type", "application/json");
					conn.setRequestProperty("Charset", "utf-8");
					OutputStream os = conn.getOutputStream();
					os.write(content.getBytes());
					os.close();
					/* 服务器返回的响应码 */
//					int code = conn.getResponseCode();
//					if (code == 200) {
						BufferedReader in = new BufferedReader(
								new InputStreamReader(conn.getInputStream(),
										"utf-8"));
						String retData = null;
						String responseData = "";
						while ((retData = in.readLine()) != null) {
							responseData += retData;
						}
						Log.e("main","返回值：转码前="+responseData);
						responseData=decodeUnicode(responseData);
						Log.e("main","返回值：转码后="+responseData);
						responseListener.onSuccess(responseData);
				} catch (Exception e) {
					Log.e("main","出错原因："+e.getMessage());
				}
				Looper.loop();
			}
		}.start();


	}

	public interface ResponseListener {
		public void onSuccess(String response);
	}
	
	public static String decodeUnicode(String theString) {      
		   
	    char aChar;      
	   
	     int len = theString.length();      
	   
	    StringBuffer outBuffer = new StringBuffer(len);      
	   
	    for (int x = 0; x < len;) {      
	   
	     aChar = theString.charAt(x++);      
	   
	     if (aChar == '\\') {      
	   
	      aChar = theString.charAt(x++);      
	   
	      if (aChar == 'u') {      
	   
	       // Read the xxxx      
	   
	       int value = 0;      
	   
	       for (int i = 0; i < 4; i++) {      
	   
	        aChar = theString.charAt(x++);      
	   
	        switch (aChar) {      
	   
	        case '0':      
	   
	        case '1':      
	   
	        case '2':      
	   
	        case '3':      
	   
	       case '4':      
	   
	        case '5':      
	   
	         case '6':      
	          case '7':      
	          case '8':      
	          case '9':      
	           value = (value << 4) + aChar - '0';      
	           break;      
	          case 'a':      
	          case 'b':      
	          case 'c':      
	          case 'd':      
	          case 'e':      
	          case 'f':      
	           value = (value << 4) + 10 + aChar - 'a';      
	          break;      
	          case 'A':      
	          case 'B':      
	          case 'C':      
	          case 'D':      
	          case 'E':      
	          case 'F':      
	           value = (value << 4) + 10 + aChar - 'A';      
	           break;      
	          default:      
	           throw new IllegalArgumentException(      
	             "Malformed   \\uxxxx   encoding.");      
	          }      
	   
	        }      
	         outBuffer.append((char) value);      
	        } else {      
	         if (aChar == 't')      
	          aChar = '\t';      
	         else if (aChar == 'r')      
	          aChar = '\r';      
	   
	         else if (aChar == 'n')      
	   
	          aChar = '\n';      
	   
	         else if (aChar == 'f')      
	   
	          aChar = '\f';      
	   
	         outBuffer.append(aChar);      
	   
	        }      
	   
	       } else     
	   
	       outBuffer.append(aChar);      
	   
	      }      
	   
	      return outBuffer.toString();      
	   
	     }

    /***
     * 加载本地Html文件的方法(file_name)
     * @param context
     * @param contentWebView
     * @param file_name
     * @param js_name
     */
    public static  void loadAssetsHtml(Context context, WebView contentWebView, String file_name,String js_name) {
        // 启用javascript
        contentWebView.getSettings().setJavaScriptEnabled(true);
        // 从assets目录下面的加载html
        contentWebView.loadUrl("file:///android_asset/html/"+file_name);
        contentWebView.addJavascriptInterface(context, js_name);
    }

    /***
     * 加载本地Html文件的方法(html_String)
     * @param context
     * @param contentWebView
     * @param html_String
     * @param js_name
     */
    public static  void loadAssetsHtmlString(Context context, WebView contentWebView, String html_String,String js_name) {
        // 启用javascript
        contentWebView.getSettings().setJavaScriptEnabled(true);

        // 从assets目录下面的加载html
//        contentWebView.loadUrl("file:///android_asset/html/"+file_name);
//        contentWebView.loadDataWithBaseURL(baseurl, html, "text/html", "UTF-8", null);
//        contentWebView.loadData( html_String, "text/html", "UTF-8");
        String baseurl="file:///android_asset/html/";
        contentWebView.loadDataWithBaseURL(baseurl, html_String, "text/html", "UTF-8", null);
        contentWebView.addJavascriptInterface(context, js_name);
    }

}
